package com.highstockings.utils;

import com.highstockings.model.Article;
import com.highstockings.model.ArticleDetailsVo;
import com.highstockings.model.ModelVo;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by diablo13064 on 2018/3/26.
 */


public class FileUtil {
    Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 把Tag列变为一个Set
     * * @param list
     *
     * @param <T>
     * @return
     */
    public static <T> List<T> enhancedTagSet(List<T> list) {
        for(int i=0;i<list.size();i++) {
            if (list.get(i) instanceof ArticleDetailsVo) {
                String thisTag =((ArticleDetailsVo)list.get(i)).getTag();
                List<String> stringArrayList = new ArrayList<>();
                stringArrayList.add(thisTag);
                ((ArticleDetailsVo)list.get(i)).setTagSet(FileUtil.tagSeperators(stringArrayList));
            }
            if (list.get(i) instanceof ModelVo) {
                String thisTag =((ModelVo)list.get(i)).getModellabel();
                List<String> stringArrayList = new ArrayList<>();
                stringArrayList.add(thisTag);
                ((ModelVo)list.get(i)).setTagSet(FileUtil.tagSeperators(stringArrayList));
            }
        }
        return list;
    }
    public static Set<String> tagSeperators(List<String> list) {
        Set<String> set = new HashSet<>();
        for(int i=0;i<list.size();i++) {
            String s = list.get(i);
            if (s==null) {
                continue;
            }
            String[] arr=null;
            if (s.contains(" ")) {
                arr = s.split(" ");
            }
            if (s.contains(",")) {
                arr = s.split(",");
            }
            if (s.contains("；")) {
                arr = s.split("；");
            }
            if (s.contains("。")) {
                arr = s.split("。");
            }
            if (s.contains(".")) {
                arr = s.split(".");
            }
            if (arr == null) {
                continue;
            }
            if (arr.length > 0) {
                for (int j = 0; j < arr.length; j++) {
                    set.add(arr[j].trim());
                }
            }
        }
        return set;
    }

    /**
     * 区分中国和外国模特套图
     *
     * @param article
     * @return
     */
    public static Map<String, String> enhancedArticleInfo(Article article) throws ParseException {
        String title = article.getTitle();
        Map<String, String> articleInfo;
        if ("XXX".contains(title) || "iMAGESET".contains(title) || "rarbg".contains(title)) {
            articleInfo = spliterForeignModel(title);
        } else {
            articleInfo = spliterChinaModel(title);
        }
        return articleInfo;
    }

    /**
     * 外国套图的信息
     *
     * @param s
     * @return
     */
    public static Map<String, String> spliterForeignModel(String s) {
        Map<String, String> map = new HashMap<>();
        int i = s.indexOf("_");
        int j = i;
        map.put("galleryType", s.substring(0, i).trim());
        try {
            Pattern pattern = Pattern.compile("\\d{2,4}\\.\\d{2}\\.\\d{2}");
            Matcher matcher = pattern.matcher(s);
            while (matcher.find()) {
                map.put("createTime", "20" + matcher.group());
                j = matcher.end();
            }
        } catch (Exception e) {

        }

        //模特名
        int k = s.indexOf(".XXX");
        try {
            map.put("modelName", s.substring(j + 1, k));
        } catch (Exception e) {

        }
        map.put("fileCounter", "(N/A)");

        map.put("fileSize", "(N/A)");
        return map;
    }
    /**
     * 根据文件名获取所有文件信息
     * @param s
     * @return
     */
    public static Map<String, String> spliterChinaModel(String s) {
        Map<String, String> map = new HashMap<>();
        //String s = "[Ugirls尤果网]2018.02.09 U343 景思晴[65P616M]";
        int x = s.indexOf("[");
        int y = s.indexOf("]");
        //System.out.println(s.substring(x+1, y));
        map.put("galleryType", s.substring(x + 1, y));
        int i = s.lastIndexOf("[");
        int j = s.lastIndexOf("]");
        //System.out.println(s.substring(i+1, j));

        //时间
        String createtime = "\\d{4}\\.\\d{2}\\.\\d{2}";
        Pattern p1 = Pattern.compile(createtime);
        Matcher matcher = p1.matcher(s);
        if (matcher.find()) {
            //System.out.println(matcher.group());
            map.put("createTime", matcher.group());
        }

        //模特名
        try {
            String modelName = "[\\u4E00-\\u9FA5]{2,8}";
            Pattern p2 = Pattern.compile(modelName);
            Matcher matcher2 = p2.matcher(s.substring(y, i));
            if (matcher2.find()) {
                //System.out.println(matcher.group());
                map.put("alias", matcher2.group());
            }
        } catch (Exception e) {
            map.put("alias", "");
        }

        //图片数
        try {
            String picsRange = s.substring(i + 1, s.indexOf("+"));
            if (Integer.parseInt(picsRange) > 0) {
                map.put("fileCounter", picsRange);
            }
        } catch (Exception e) {
            String fileCounter = "\\d{1,}P";
            Pattern p3 = Pattern.compile(fileCounter);
            Matcher matcher3 = p3.matcher(s.substring(i, j));
            if (matcher3.find()) {
                //System.out.println(matcher3.group());
                map.put("fileCounter", matcher3.group().replace("P",""));
            }
        }
        try {
            String fileSize = "\\d{1,}M";
            Pattern p4 = Pattern.compile(fileSize);
            Matcher matcher4 = p4.matcher(s.substring(i, j));
            while (matcher4.find()) {
                map.put("fileSize", matcher4.group());
            }
        } catch (Exception e) {

        }
        //图片大小


        return map;
    }


    /**
     * 写文件
     * @param is
     * @param os
     * @throws IOException
     */
    public static void writeFile(InputStream is, OutputStream os) throws IOException {
        FileCopyUtils.copy(is, os);
    }

    /**
     * 删除文件夹下所有文件
     * @param file
     */
    public static void DeleteAllFile(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    f.delete();
                }
            } else if (file.isFile()) {
                file.delete();
            }
        }
    }

    /**
     * 删除文件夹些所有指定后缀的文件
     * @param file
     * @param filter
     */
    public static void DeleteAllFile(File file,String filter) {
        if (file.exists()) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    if (f.getName().endsWith(filter)) {
                        f.delete();
                    }
                }
            } else if (file.isFile()) {
                if (file.getName().endsWith(filter)) {
                    file.delete();
                }
            }
        }
    }


    /**
     * 文件到Byte
     * @param filePath
     * @return
     */
    public static byte[] File2byte(String filePath)
    {
        byte[] buffer = null;
        try
        {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * Byte到文件
     * @param buf
     * @param filePath
     * @param fileName
     */
    public static void byte2File(byte[] buf, String filePath, String fileName)
    {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try
        {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory())
            {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String Date2String(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static Date String2Date(String s, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(s);
    }
}
